﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using TelerikConnect.Models;
using TelerikConnect.Web.DBConnect;

namespace TelerikConnect.Web.Controllers
{
    [Authorize]
    public class UpdatesController : Controller
    {
        private readonly TelerikDb db = new TelerikDb();

        public ActionResult PostUpdate()
        {
            return View();
        }

        [HttpPost]
        public ActionResult PostUpdate(string content)
        {
            db.Updates.Add(new UpdateModel
                {
                    Author = db.UserProfiles.Single(u => u.UserName == User.Identity.Name),
                    Content = content,
                    PostDate = DateTime.Now
                });

            db.SaveChanges();

            return Redirect("/");
        }

        public ActionResult GetUpdates()
        {
            List<string> followed = db.Followers.Where(f => f.Follower.UserName == User.Identity.Name).Select(f => f.Followed.UserName).ToList();

            followed.Add(User.Identity.Name);

            var updates = db.Updates.Where(u => followed.Contains(u.Author.UserName)).Select(
                u => new
                {
                    Avatar = u.Author.Avatar,
                    Author = u.Author.UserName,
                    FirstName = u.Author.FirstName,
                    LastName = u.Author.LastName,
                    Content = u.Content,
                    PostDate = u.PostDate
                }
                ).Take(10).OrderByDescending(d => d.PostDate);

            return Json(updates, JsonRequestBehavior.AllowGet);
        }
    }
}